<template>
  <div class="content-box-full">
    <ContainerBox>
      <template #header>
        <el-form
          @keyup.enter.native="handleSearch"
          ref="formRef"
          :model="searchForm"
          label-width="auto"
          inline
        >
          <el-form-item label="消费时段编号:" prop="consumptionPeriodNo">
            <el-input v-model="searchForm.consumptionPeriodNo" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="消费时段名称:" prop="consumptionPeriodName">
            <el-input v-model="searchForm.consumptionPeriodName" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button
              v-permission="'hire:consumptionplan:list'"
              type="primary"
              @click="handleSearch"
              >查询
            </el-button>
            <el-button
              v-permission="'hire:consumptionplan:save'"
              @click="handleAdd"
              v-prevent-reclick="{ delay: 300 }"
            >
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-table
          :data="tableData"
          :empty-text="isLoadingTable ? '加载中...' : '暂无数据'"
          class="table-box"
          height="100%"
          stripe
          fit
          border
          row-key="id"
          highlight-current-row
        >
          <el-table-column type="index" align="center" label="序号" width="100"></el-table-column>
          <el-table-column label="消费时段编号" align="center" min-width="200" prop="code">
            <template #default="{ row, column }">
              <el-input v-if="row._isEdit_" v-model="row[column.property]"></el-input>
              <span v-else>{{ row[column.property] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费时段名称" align="center" min-width="200" prop="name">
            <template #default="{ row, column }">
              <el-input v-if="row._isEdit_" v-model="row[column.property]"></el-input>
              <span v-else>{{ row[column.property] }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" min-width="200">
            <template #default="{ row, $index }">
              <template v-if="row._isEdit_">
                <el-button @click="saveRow(row, $index)">保存</el-button>
                <el-button @click="tableData.splice($index, 1)">取消</el-button>
              </template>
              <template v-else>
                <el-button v-permission="'hire:consumptionplan:update'" @click="editRow(row)"
                  >编辑
                </el-button>
                <el-button v-permission="'hire:consumptionplan:delete'" @click="deleteRow(row)"
                  >删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <CommonPaging
          :total="tableTotal"
          :current-page="pageNum"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
        ></CommonPaging>
      </template>
    </ContainerBox>
    <el-dialog
      lock-scroll
      top="10vh"
      class="common-el-dialog"
      v-model="showDialog"
      :title="'编辑消费时段'"
      width="900"
      @close="handleClose"
    >
      <el-table
        :data="periodTableData"
        class="table-box"
        height="100%"
        stripe
        fit
        border
        :empty-text="periodLoadingTable ? '加载中...' : '暂无数据'"
        highlight-current-row
      >
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="时段名称" min-width="100" align="center" prop="name">
          <template #header="{ column }">
            <span class="required-star">{{ column.label }}</span>
          </template>
          <template #default="{ row, column }">
            <el-select v-model="row[column.property]">
              <el-option
                v-for="item in PERIOD_TIME_LIST"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" min-width="120" align="center" prop="startDate">
          <template #header="{ column }">
            <span class="required-star">{{ column.label }}</span>
          </template>
          <template #default="{ row, column }">
            <el-time-select
              :max-time="row['endDate']"
              v-model="row[column.property]"
              start="00:00"
              step="00:01"
              end="24:00"
            />
          </template>
        </el-table-column>
        <el-table-column label="结束时间" min-width="120" align="center" prop="endDate">
          <template #header="{ column }">
            <span class="required-star">{{ column.label }}</span>
          </template>
          <template #default="{ row, column }">
            <el-time-select
              :min-time="row['startDate']"
              v-model="row[column.property]"
              start="00:00"
              step="00:01"
              end="24:00"
            />
          </template>
        </el-table-column>
        <el-table-column label="定价" min-width="100" align="center" prop="amount">
          <template #default="{ row, column }">
            <el-input v-model.number="row[column.property]"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="限次" min-width="100" align="center" prop="consumptionCount">
          <template #default="{ row, column }">
            <el-input v-model.number="row[column.property]"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="消费模式" min-width="120" align="center" prop="consumptionPattern">
          <template #header="{ column }">
            <span class="required-star">{{ column.label }}</span>
          </template>
          <template #default="{ row, column }">
            <el-select v-model="row[column.property]">
              <el-option
                v-for="item in PERIOD_MODE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button  v-prevent-reclick :disabled="periodLoadingTable" type="primary" @click="handleFormSubmit">
            确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue'
import ContainerBox from '@/components/base/ContainerBox.vue'
import CommonPaging from '@/components/base/CommonPaging.vue'
import message from '@/utils/elMessage.js'
import { PERIOD_MODE, PERIOD_TIME_LIST } from '@/utils/systemConfig.js'
import consumptionPeriodApi from '@/api/consumptionPeriodApi.js'

const { proxy } = getCurrentInstance()
onMounted(() => {
  fetchList()
})
const searchForm = ref({
  consumptionPeriodNo: '', //消费时段编号
  consumptionPeriodName: '', //消费时段名称
})
const pageNum = ref(1)
const pageSize = ref(10)

//查询
function handleSearch() {
  handleCurrentChange(1)
}

function fetchList() {
  isLoadingTable.value = true
  tableData.value = []
  const params = {
    page: pageNum.value,
    limit: pageSize.value,
    code: searchForm.value.consumptionPeriodNo,
    name: searchForm.value.consumptionPeriodName,
  }
  consumptionPeriodApi
    .fetchList(params)
    .then((res) => {
      if (res.code === 0) {
        const data = res.page || {}
        tableTotal.value = data.totalCount || 0
        tableData.value = data.list || []
      } else {
        message.warning(res.msg)
      }
    })
    .finally(() => {
      isLoadingTable.value = false
    })
}

// 列表数据
const isLoadingTable = ref(false)
const tableData = ref([])
const tableTotal = ref(0)

function saveRow(row, rowIndex) {
  const { code, name } = row
  if (!code) {
    message.warning('消费时段编号不可以为空！')
    return
  }
  if (!name) {
    message.warning('消费时段名称不可以为空')
    return
  }
  const params = {
    code,
    name,
  }
  consumptionPeriodApi.save(params).then((res) => {
    if (res.code === 0) {
      tableData.value[rowIndex]['_isEdit_'] = false
      //保存后 设置当前行id为后台返回的行id  用于编辑和删除
      tableData.value[rowIndex]['id'] = res.id
      message.success(res.msg)
    } else {
      message.warning(res.msg)
    }
  })
}

function deleteRow(row) {
  if (row.code) {
    message.confirm('您是否确定要删除该消费时段?', '提示').then(() => {
      consumptionPeriodApi
        .delete([row.code])
        .then((res) => {
          if (res.code === 0) {
            message.success(res.msg)
            const deleteIndex = tableData.value.findIndex((el) => el.code === row.code)
            if (deleteIndex !== -1) {
              tableData.value.splice(deleteIndex, 1)
            } else {
              fetchList()
            }
          } else {
            message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.error(error.messages)
        })
    })
  }
}

function handleCurrentChange(val) {
  pageNum.value = val
  fetchList()
}

function handleSizeChange(val) {
  pageNum.value = 1
  pageSize.value = val
  fetchList()
}

// 新增食堂相关
const showDialog = ref(false)
// 消费时段编辑
const periodTableData = ref([])
const periodLoadingTable = ref(false)
const isAdd = ref(true)
//新增默认值
const INIT_TABLE_DATA = [
  {
    id: 1,
    name: 'breakfast',
    startDate: '',
    endDate: '',
    amount: '',
    consumptionCount: '',
    consumptionPattern: '',
  },
  {
    id: 2,
    name: 'lunch',
    startDate: '',
    endDate: '',
    amount: '',
    consumptionCount: '',
    consumptionPattern: '',
  },
  {
    id: 3,
    name: 'dinner',
    startDate: '',
    endDate: '',
    amount: '',
    consumptionCount: '',
    consumptionPattern: '',
  },
  {
    id: 4,
    name: 'nightSnack',
    startDate: '',
    endDate: '',
    amount: '',
    consumptionCount: '',
    consumptionPattern: '',
  },
  {
    id: 5,
    name: 'lateNightSnack',
    startDate: '',
    endDate: '',
    amount: '',
    consumptionCount: '',
    consumptionPattern: '',
  },
]

//新增
function handleAdd() {
  const addRowInfo = {
    id: proxy.$utils.getUUID(),
    _isEdit_: true,
    code: '',
    name: '',
  }
  tableData.value.push(addRowInfo)
}

function handleClose() {
  // dataFormRef.value.resetFields()/
}

function editRow(row) {
  periodLoadingTable.value = true
  showDialog.value = true
  consumptionPeriodApi
    .checkContent(row.id)
    .then((res) => {
      if (res.code === 0) {
        //有值 说明是编辑
        if ((res.consumptionContent || []).length) {
          isAdd.value = false
          periodTableData.value = res.consumptionContent || []
        } else {
          isAdd.value = true
          for (let i = 0, j = INIT_TABLE_DATA.length; i < j; i++) {
            INIT_TABLE_DATA[i]['consumptionPlanId'] = row.id
          }
          periodTableData.value = proxy.$utils.deepClone(INIT_TABLE_DATA)
        }
        // showDialog.value = true
      } else {
        message.warning(res.msg)
      }
    })
    .finally(() => {
      periodLoadingTable.value = false
    })
}

function handleFormSubmit() {
  let validateFlag = true
  let validateIndex = 0
  for (let i = 0, l = periodTableData.value.length; i < l; i++) {
    const { name, startDate = '', endDate = '', consumptionPattern } = periodTableData.value[i]
    if (name === '' || startDate === '' || endDate === '' || consumptionPattern === '') {
      validateFlag = false
      validateIndex = i
      break
    }
  }
  if (validateFlag) {
    const fetchApi = isAdd.value
      ? consumptionPeriodApi.saveContent
      : consumptionPeriodApi.updateContent
    fetchApi(periodTableData.value).then((res) => {
      if (res.code === 0) {
        message.success(res.msg)
        showDialog.value = false
      } else {
        message.warning(res.msg)
      }
    })
  } else {
    message.warning(`第${validateIndex + 1}行存在必填项为空！`)
  }
}
</script>
